/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package econutri.servicos.sujestao;

import econutri.persistencia.entidades.Alimento;
import econutri.util.Utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lomtools.persistence.GenericDAO;

/**
 *
 * @author Leonardo Oliveira Moreira
 * 
 */
public class ProcessarSugestaoAlimentoXMLServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/xml;charset=ISO-8859-1");
        String xml = "";
        String pacienteCodigo = request.getParameter("pacienteCodigo");
        String recordatorioData = request.getParameter("recordatorioData");

        List<AlimentoSugestao> alimentoList = new ArrayList<AlimentoSugestao>();
        Enumeration<String> parameterNames = request.getParameterNames();
        List<String> variavelList = new ArrayList<String>();
        while (parameterNames.hasMoreElements()) {
            String param = parameterNames.nextElement();
            if (param.startsWith("X")) {
                variavelList.add(param);
            }
        }
         int x = 1;
        while (variavelList.size() > 0) {
            for (int i = 0; i < variavelList.size(); i++) {
                if (variavelList.get(i).equals("X" + x)) {
                    String value = request.getParameter(variavelList.get(i));
                    String[] valueSplit = value.split("@");
                    AlimentoSugestao a = new AlimentoSugestao();
                    a.setVariavel(variavelList.get(i));
                    a.setCodigo(Long.parseLong(valueSplit[0]));
                    a.setQuantidade(Double.parseDouble(valueSplit[1]));
                    alimentoList.add(a);
                    variavelList.remove(i);
                    x++;
                    break;
                }
            }
        }
        double totalCalorias = 0;
        for (Alimento a : alimentoList) {
            Double quantidadeRequerida = a.getQuantidade();
            String sql = "select codigo, descricao, quantidade, carboidrato, proteina, lipidio, calcio, fosforo, ferro, sodio, vitaminaa, vitaminab1, vitaminab2, niacina, vitaminac, fibra, colesterol, preco from alimento where codigo = " + a.getCodigo();
            try {
                GenericDAO dao = new GenericDAO();

                ResultSet rs = dao.executeQuery(sql);
                
                while (rs != null && rs.next()) {

                    a.setCodigo(rs.getLong("codigo"));
                    a.setDescricao(rs.getString("descricao"));
                    Double quantidade = (rs.getDouble("quantidade") / 100);
                    a.setQuantidade(quantidadeRequerida * quantidade);

                    Double carboidrato = (rs.getDouble("carboidrato") / 100);
                    a.setCarboidrato(quantidadeRequerida * (Utils.formatDoubleValue(carboidrato)));
                    Double proteina = (rs.getDouble("proteina") / 100);
                    a.setProteina(quantidadeRequerida * (Utils.formatDoubleValue(proteina)));
                    Double lipidio = (rs.getDouble("lipidio") / 100);
                    a.setLipidio(quantidadeRequerida * (Utils.formatDoubleValue(lipidio)));

                    a.setCalcio(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("calcio") / 100)));
                    a.setFosforo(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("fosforo") / 100)));
                    a.setFerro(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("ferro") / 100)));
                    a.setSodio(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("sodio") / 100)));
                    a.setVitaminaA(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("vitaminaa") / 100)));
                    a.setVitaminaB1(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("vitaminab1") / 100)));
                    a.setVitaminaB2(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("vitaminab2") / 100)));
                    a.setNiacina(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("niacina") / 100)));
                    a.setVitaminaC(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("vitaminac") / 100)));
                    a.setFibra(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("fibra") / 100)));
                    a.setColesterol(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("colesterol")) / 100));

                    a.setPreco(quantidadeRequerida * (Utils.formatDoubleValue(rs.getDouble("preco") / 100)));

                    totalCalorias += (quantidadeRequerida * Utils.getCalorias(quantidade, carboidrato, proteina, lipidio));
                }
                
                dao.close();

            } catch (SQLException ex) {
                a = null;
            }
        }

        xml += "<result>";
            xml += "<paciente>";
                xml += "<codigo>" + pacienteCodigo + "</codigo>";
            xml += "</paciente>";
            xml += "<alimentos>";
            for (int i = 0; i < alimentoList.size(); i++) {
                AlimentoSugestao a = alimentoList.get(i);
                xml += "<alimento>";
                    xml += "<variavel>" + a.getVariavel() + "</variavel>";
                    xml += "<codigo>" + a.getCodigo() + "</codigo>";
                    xml += "<descricao>" + a.getDescricao() + "</descricao>";
                    xml += "<quantidade>" + a.getQuantidade() + "</quantidade>";

                    xml += "<carboidrato>" + a.getCarboidrato() + "</carboidrato>";
                    xml += "<proteina>" + a.getProteina() + "</proteina>";
                    xml += "<lipidio>" + a.getLipidio() + "</lipidio>";

                    xml += "<calcio>" + a.getCalcio() + "</calcio>";
                    xml += "<fosforo>" + a.getFosforo() + "</fosforo>";
                    xml += "<ferro>" + a.getFerro() + "</ferro>";

                    xml += "<sodio>" + a.getSodio() + "</sodio>";
                    xml += "<vitaminaa>" + a.getVitaminaA() + "</vitaminaa>";
                    xml += "<vitaminab1>" + a.getVitaminaB1() + "</vitaminab1>";

                    xml += "<vitaminab2>" + a.getVitaminaB2() + "</vitaminab2>";
                    xml += "<niacina>" + a.getNiacina() + "</niacina>";
                    xml += "<vitaminac>" + a.getVitaminaC() + "</vitaminac>";

                    xml += "<fibra>" + a.getFibra() + "</fibra>";
                    xml += "<colesterol>" + a.getColesterol() + "</colesterol>";

                    xml += "<preco>" + a.getPreco() + "</preco>";

                    try {
                        GenericDAO dao = new GenericDAO();
                        ResultSet rs = dao.executeQuery(
                            "select ri.alimentocodigo, ri.refeicaocodigo, ref.descricao as refeicaodescricao " +
                            "from recordatorio r, recordatorioitem ri, refeicao ref " +
                            "where r.pacientecodigo = " + pacienteCodigo + " and " +
                            "r.data = '" + Utils.converterDataSQL(recordatorioData) + "' and " +
                            "alimentocodigo = " + a.getCodigo() + " and " +
                            "r.pacientecodigo = ri.pacientecodigo and " +
                            "r.data = ri.data and ri.refeicaocodigo = ref.codigo");
                        while (rs != null && rs.next()) {
                            xml += "<refeicaocodigo>" + rs.getLong("refeicaocodigo") + "</refeicaocodigo>";
                            xml += "<refeicaodescricao>" + rs.getString("refeicaodescricao") + "</refeicaodescricao>";
                        }
                        dao.close();
                    } catch (SQLException ex) {
                        xml += "<refeicaocodigo>" + "-1" + "</refeicaocodigo>";
                        xml += "<refeicaodescricao>" + "Não definido" + "</refeicaodescricao>";
                    }
                xml += "</alimento>";
            }
            xml += "</alimentos>";
            xml += "<totais>";
                double totalCarboidrato = 0;
                double totalProteina = 0;
                double totalLipidio = 0;
                double totalCalcio = 0;
                double totalFosforo = 0;
                double totalFerro = 0;
                double totalSodio = 0;
                double totalVitaminaA = 0;
                double totalVitaminaB1 = 0;
                double totalVitaminaB2 = 0;
                double totalNiacina = 0;
                double totalVitaminaC = 0;
                double totalFibra = 0;
                double totalColesterol = 0;
                double totalCusto = 0;
                for (AlimentoSugestao a : alimentoList) {
                    totalCarboidrato += (a.getCarboidrato());
                    totalProteina += (a.getProteina());
                    totalLipidio += (a.getLipidio());
                    totalCalcio += (a.getCalcio());
                    totalFosforo += (a.getFosforo());
                    totalFerro += (a.getFerro());
                    totalSodio += (a.getSodio());
                    totalVitaminaA += (a.getVitaminaA());
                    totalVitaminaB1 += (a.getVitaminaB1());
                    totalVitaminaB2 += (a.getVitaminaB2());
                    totalNiacina += (a.getNiacina());
                    totalVitaminaC += (a.getVitaminaC());
                    totalFibra += (a.getFibra());
                    totalColesterol += (a.getColesterol());
                    totalCusto += (a.getPreco());
                }
                xml += "<totalCarboidrato>" + Utils.formatDoubleValue(totalCarboidrato) + "</totalCarboidrato>";
                xml += "<totalProteina>" + Utils.formatDoubleValue(totalProteina) + "</totalProteina>";
                xml += "<totalLipidio>" + Utils.formatDoubleValue(totalLipidio) + "</totalLipidio>";
                xml += "<totalCalcio>" + Utils.formatDoubleValue(totalCalcio) + "</totalCalcio>";
                xml += "<totalFosforo>" + Utils.formatDoubleValue(totalFosforo) + "</totalFosforo>";
                xml += "<totalFerro>" + Utils.formatDoubleValue(totalFerro) + "</totalFerro>";
                xml += "<totalSodio>" + Utils.formatDoubleValue(totalSodio) + "</totalSodio>";
                xml += "<totalVitaminaA>" + Utils.formatDoubleValue(totalVitaminaA) + "</totalVitaminaA>";
                xml += "<totalVitaminaB1>" + Utils.formatDoubleValue(totalVitaminaB1) + "</totalVitaminaB1>";
                xml += "<totalVitaminaB2>" + Utils.formatDoubleValue(totalVitaminaB2) + "</totalVitaminaB2>";
                xml += "<totalNiacina>" + Utils.formatDoubleValue(totalNiacina) + "</totalNiacina>";
                xml += "<totalVitaminaC>" + Utils.formatDoubleValue(totalVitaminaC) + "</totalVitaminaC>";
                xml += "<totalFibra>" + Utils.formatDoubleValue(totalFibra) + "</totalFibra>";
                xml += "<totalColesterol>" + Utils.formatDoubleValue(totalColesterol) + "</totalColesterol>";
                xml += "<totalCusto>" + Utils.treatValue(Utils.formatDoubleValue(totalCusto)) + "</totalCusto>";
                xml += "<totalCalorias>" + Utils.formatDoubleValue(totalCalorias) + "</totalCalorias>";
            xml += "</totais>";
        xml += "</result>";
        PrintWriter out = response.getWriter();
        try {
            out.println(xml);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
